<?php

declare(strict_types=1);

namespace App\Controller;


use App\Model\Role;
use App\Model\User;
use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;


/**
 * Class UserController
 * @package App\Controller
 */
class UserController extends AbstractController
{

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        $pageSize = (int)$request->input('pageSize', 10);
        $inputs = $request->inputs(['keyword', 'orderByKey', 'orderDirection']);
        $records = User::query()->where(function (Builder $builder) use (&$inputs) {
            if ($inputs['keyword']) {
                $builder->where('username', 'like', sprintf('%%%s%%', $inputs['keyword']))
                    ->orWhere('nickname', 'like', sprintf('%%%s%%', $inputs['keyword']));
            }
        })->orderBy($inputs['orderByKey'] ?? 'id', $inputs['orderDirection'] ?? 'desc')->paginate($pageSize, ['*'], 'current');
        $items = $records->items();
        array_walk($items, function ($item) {
            $item->avatar_url = $item->avatar[0]['url'] ?? '';
        });

        return $response->json([
            'pagination' => [
                'total' => $records->total(),
                'pageSize' => $pageSize,
                'current' => $records->currentPage()

            ],
            'list' => $items
        ]);
    }

    public function save(int $id, RequestInterface $request, ResponseInterface $response)
    {

        $inputs = $request->inputs(['nickname', 'avatar', 'username', 'password', 'email', 'status']);
        $roleIds = $request->input('role_ids', []);

        $record = User::query()->where('username', $inputs['username'])->first();
        if ($record && (int)$record->id !== $id) {
            return $response->json(['message' => '用户名已存在', 'status' => STATUS_FAILURE]);
        }
        $user = User::query()->updateOrCreate(['id' => $id], $inputs);
        /**
         * @var \App\Model\User $user
         */
        $user->roles()->sync($roleIds);

        return $response->json(['message' => '操作成功', 'status' => STATUS_SUCCESS]);
    }

    public function detail(int $id, ResponseInterface $response)
    {

        if ($id) {
            $record = User::query()->where(['id' => $id])->first();
            if ($record) {
                $roleIds = Db::table('user_role')->where('user_id', $record->id)->pluck('role_id')->toArray();
            }
        }
        return $response->json([
            'data' => !empty($record) ? ($record->toArray() + ['role_ids' => $roleIds ?? []]) : [],
            'roles' => Role::all()->toArray()
        ]);
    }

    public function batchDelete(RequestInterface $request, ResponseInterface $response)
    {
        $ids = $request->input('ids');
        User::query()->where('id', $ids)->delete();
        return $response->json(['message' => '操作成功', 'status' => STATUS_SUCCESS]);
    }
}
